package com.jeeplus.test.jlnu.admissionInfo.utils;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.poi.ss.usermodel.*;

import java.util.HashMap;
import java.util.Map;

public class GrayStyleHandler implements CellWriteHandler {

    private final int lockColumnCount;
    private final Map<Workbook, CellStyle> grayStyleCache = new HashMap<>();

    public GrayStyleHandler(int lockColumnCount) {
        this.lockColumnCount = lockColumnCount;
    }

    @Override
    public void afterCellDispose(CellWriteHandlerContext context) {
        // 判断不是表头
        if (BooleanUtils.isNotTrue(context.getHead())) {
            Cell cell = context.getCell();
            Workbook workbook = context.getWriteWorkbookHolder().getWorkbook();

            // 复用已缓存的样式
            CellStyle grayStyle = grayStyleCache.computeIfAbsent(workbook, this::createGrayStyle);

            // 获取当前行的样式
            CellStyle cellStyle = workbook.createCellStyle();

            // 只对前 `lockColumnCount` 列生效
            if (cell.getColumnIndex() < lockColumnCount) {
                cellStyle.setFillForegroundColor(IndexedColors.RED1.getIndex());
                cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                cellStyle.setBorderTop(BorderStyle.THIN);
                cellStyle.setBorderBottom(BorderStyle.THIN);
                cellStyle.setBorderLeft(BorderStyle.THIN);
                cellStyle.setBorderRight(BorderStyle.THIN);
                // 设置锁定单元格
                cellStyle.setLocked(true);  // 锁定当前单元格
            } else {
                // 对其他单元格设置解锁
                cellStyle.setLocked(false);  // 解锁当前单元格
            }

            // 设置单元格样式
            cell.setCellStyle(cellStyle);

            // 清除默认的 WriteCellStyle，防止 FillStyleCellWriteHandler 覆盖我们自定义的样式
            WriteCellData<?> cellData = context.getFirstCellData();
            cellData.setWriteCellStyle(null);
        }
    }

    /**
     * 创建灰色背景的 CellStyle
     */
    private CellStyle createGrayStyle(Workbook workbook) {
        CellStyle grayStyle = workbook.createCellStyle();
        grayStyle.setFillForegroundColor(IndexedColors.RED1.getIndex());
        grayStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        grayStyle.setBorderTop(BorderStyle.THIN);
        grayStyle.setBorderBottom(BorderStyle.THIN);
        grayStyle.setBorderLeft(BorderStyle.THIN);
        grayStyle.setBorderRight(BorderStyle.THIN);
        return grayStyle;
    }

    /**
     * 启用工作表保护
     * 需要在调用 `afterCellDispose` 后启用工作表保护，设置哪些单元格是锁定的。
     */
    public void enableSheetProtection(Sheet sheet) {
        // 启用工作表保护
        sheet.protectSheet("password"); // 这里可以设置密码，只有输入正确密码后才能编辑锁定的单元格
    }
}
